package com.douziit.meilianoa.base.generator;



import com.douziit.meilianoa.base.utils.JacksonUtil;
import com.douziit.meilianoa.base.utils.StrEncryptUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.interceptor.KeyGenerator;

import java.lang.reflect.Method;

/**
 * 自定义缓存生成规则
 *
 * @author MrShun
 * @version 1.0
 * @Date 2017/11/25
 */
public class CacheKeyGenerator implements KeyGenerator {

    private final Logger logger = LoggerFactory.getLogger(CacheKeyGenerator.class);

    @Override
    public Object generate(Object target, Method method, Object... params) {
        return encodeStr(target, method, params);
    }

    /**
     * 自定义生成EhCache Key
     *
     * @param target
     * @param method
     * @param params
     * @return
     */
    private String encodeStr(Object target, Method method, Object... params) {
        String classesName = target.getClass().getSimpleName();
        String key = "[".concat(classesName).concat(".").concat(method.getName()).concat("(").concat(StrEncryptUtil.md5(JacksonUtil.obj2json(params))).concat(")]");
        logger.debug("cache key > {}", key);
        return key;
    }
}
